//
//  BGUserAccountViewModel.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/23.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit

class BGUserAccountViewModel: NSObject {
    
    //全局访问点
    static let sharedTools: BGUserAccountViewModel = BGUserAccountViewModel()
    
    //创建一个用户模型
    var userAccount: BGUserAccountModel?
    
    //使用计算型
    //accessToken
    var accessToken: String? {
        
        //判断是否有accessToken
        if userAccount?.access_token != nil {
            //有accessToken 
            //判断是否过期,添加一个保存日期的属性
            //当前保存日期和当前日期比如果是降序就是未过期
            if userAccount?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                //没过期则可以返回access_token
                return userAccount?.access_token
                
            }else {
                //过期了
                return nil
            }
        }else {
            //没有accessToken
            return nil
        }
    }
    
    //用accessToken是否存在判断是否登录
    var isLogin: Bool{
        return accessToken != nil
    }
    
    override init() {
        super.init()
        userAccount = getUserAccount()
    }
    
    private let file = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccountModel.model")
    
}

//MARK: - 归档解档
extension BGUserAccountViewModel {
    //归档
    func saveUserAccount(userAccount: BGUserAccountModel) {
        self.userAccount = userAccount
        //归档
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.file)
    }
    
    //解档
    func getUserAccount() -> BGUserAccountModel? {
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? BGUserAccountModel
        return result
    }
}

//MARK: - 请求数据
extension BGUserAccountViewModel {
    
    //请求获取accessToken
    func loadAccessToken(code: String, isSuccess: (isSucc: Bool) -> ()) {
        //请求获得accessToken
        BGNetworkTools.shareTools.oauthLoadAccessToken(code, success: { (response) in
            //判断response是否为nil,是否可以转为模型
            guard let res = response as? [String: AnyObject] else {
                isSuccess(isSucc: false)
                return
            }
            //将字典转模型
            let userAccessModel = BGUserAccountModel(dict: res)
            
            //获取用户信息
            self.loadUserInfo(userAccessModel, isSuccess: isSuccess)
            
            }) { (error) in
                print("获取accessToken失败\(error)")
                isSuccess(isSucc: false)
        }
        
    }
    
    //获取用户数据
    func loadUserInfo(userAccountModel: BGUserAccountModel, isSuccess: (isSucc: Bool) -> ()) {
        BGNetworkTools.shareTools.oauthLoadUserInfo(userAccountModel, success: { (response) in
            
            //判断response能否转字典
            guard let res = response as? [String: AnyObject] else {
                isSuccess(isSucc: false)
                return
            }
            
            //给用户模型赋值
            userAccountModel.screen_name = res["screen_name"] as? String
            userAccountModel.avatar_large = res["avatar_large"] as? String
            //保存用户数据
            self.saveUserAccount(userAccountModel)
            isSuccess(isSucc: true)
            }) { (error) in
                print("获取userInfo失败\(error)")
                isSuccess(isSucc: false)
        }
        
    }

}

